﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Xml.Linq;
using QDP.Platform.IO;
using QDP.Platform.Silverlight;
namespace QDP.Platform.Loader
{
    public partial class SplasnScreen : UserControl
    {
        const string LOAD_PLATFROM_COMMON = "LOAD_PLATFROM_COMMON";
        const string NAVIGAT_CUSTOM_LOGON = "NAVIGAT_CUSTOM_LOGON";
        const string GET_SETTING_LOSE = "GET_SETTING_LOSE";
        const string AUTORUN_IS_NULL = "AUTORUN_IS_NULL";
        const string URL_IS_NULL = "URL_IS_NULL";
        const string REQUEST_USER = "REQUEST_USER";
        const string REQUEST_USER_LOSE = "REQUEST_USER_LOSE";
        const string REQUEST_USER_SUCCESS = "REQUEST_USER_SUCCESS";
        const string REQUEST_OPTION = "REQUEST_OPTION";
        const string REQUEST_OPTION_ERROR = "REQUEST_OPTION_ERROR";
        const string REQUEST_OPTION_SUCCESS = "REQUEST_OPTION_SUCCESS";

        const string LANGUAGE_KEY = "Language";

        const string set_format = "(.+?)\\|(.+?);";

        private Identity currentUser;
        public SplasnScreen()
        {
            InitializeComponent();
            this.HideLayoutRoot.Completed += HideLayoutRoot_Completed;
            this.RequestSets();
        }

        #region 1.请求平台参数 相关
        private List<DownloadFile> Files;
        /// <summary>请求平台参数反馈方法。</summary>
        /// <param name="success">请求操作结果</param>
        /// <param name="result">请求操作返回文本内容。</param>
        private void RequestSetsCallback(bool success, string result)
        {
            // 读取内容失败 ：提示并退出
            if (success == false)
            {
                SetSplashScreenText(result);
                D.Debug(result);
                return;
            }

            var doc = XDocument.Parse(result);
            var root = doc.Root;
            // 读取sets节点配置信息
            var sets = from element in root.Element("sets").Elements() select element;
            foreach (var set in sets)
            {
                string key = set.Attribute("key").Value;
                string value = set.Attribute("value").Value;
                Q.ConfigManager.AddSet(key, value);
            }
            // 读取files节点配置信息
            var files = from element in root.Element("files").Elements() select element;
            foreach (var file in files)
            {
                string key = file.Attribute("mode").Value;
                string value = file.Attribute("url").Value;
                Files.Add(new DownloadFile() { File = value, Mode = key });
            }
            // 读取urls节点配置信息
            var urls = from element in root.Element("urls").Elements() select element;
            foreach (var url in urls)
            {
                string key = url.Attribute("key").Value;
                string value = url.Attribute("value").Value;
                Q.ConfigManager.AddUrl(key, value);
            }

            // 合并url请求参数与平台配置参数
            // 处理url请求参数
            foreach (KeyValuePair<string, string> pair in (Application.Current as App).Configurations)
            {
                Q.ConfigManager.AddSet(pair.Key, pair.Value);
            }

            RequestLanguagePack();
            D.Debug("请求参数完成.");
        }
        /// <summary>1.请求平台参数设置 相关</summary>
        private void RequestSets()
        {
            this.Files = new List<DownloadFile>();
            D.Debug("请求参数.");
            Q.ConfigManager.Read(this.RequestSetsCallback);
        }
        #endregion //1.请求平台参数设置

        #region 2.请求语言包 相关
        private void RequestLanguagePack()
        {
            D.Debug("请求语言包.");
            string url = Q.ConfigManager.GetUrl("language");
            // 查看参数设置中是否包含语言设置；
            url += "?l=" + Q.ConfigManager.GetSet(LANGUAGE_KEY);
            D.Debug(url);
            Q.ConfigManager.Request(url, (success, r) =>
            {
                // 读取内容失败 ：提示并退出
                if (success == false)
                {
                    SetSplashScreenText(r);
                    D.Debug(r);
                    return;
                }

                foreach (Match m in Regex.Matches(r, set_format))
                {
                    if (m.Success)
                    {
                        string key = m.Groups[1].Value;
                        string value = m.Groups[2].Value;
                        Q.ConfigManager.AddText(key, value);
                    }
                }
                this.StartDownload();
                D.Debug("请求语言包完成.");
            });
        }
        private string LanguageText(string key)
        {
            return Q.ConfigManager.GetText(key);
        }
        #endregion //#region 2.请求语言包 相关

        #region 3.文件下载 相关
        private Downloader downloader;
        public event EventHandler DownloadComplated;
        // 启动文件下载
        private void StartDownload()
        {
            D.Debug("准备下载文件");
            if (downloader == null)
            {
                downloader = new Downloader();
                // 注册下载完成事件
                downloader.DownloadCompleted += downloader_DownloadCompleted;
                // 注册下载进度事件
                downloader.DownloadProgressChanged += downloader_DownloadProgressChanged;
                // 注册下载错误事件
                downloader.ErrorAccured += downloader_ErrorAccured;
            }
            SetSplashScreenText(LanguageText(LOAD_PLATFROM_COMMON));
            this.ToDoNext(true);
        }
        private void ToDoNext(bool first=false)
        {
            if (first == false)
            {
                // 文件解析完成后需移除当前处理的文件
                Files.RemoveAt(0);
            }
            // 在移除已经处理的文件后，判断是否还有需要下载解析的资源，若有，则继续下载，否则开始初始化平台。
            if (Files.Count == 0)
            {
                this.RequestUserIdentity();
            }
            else
            {
                D.Debug(Files[0].File);
                SetSplashScreenUri(Files[0].File);
                downloader.DownloadFile(Files[0].File);
            }
        }
        // 下载发生错误时，可讲错误提示反馈给用户界面。
        void downloader_ErrorAccured(object sender, FileDownloadErrorAccured e)
        {
            D.Debug("err:"+e.Exception.Message);
            this.ToDoNext();
        }
        // 下载进度变更时，可对用户界面进行相应。
        void downloader_DownloadProgressChanged(object sender, FileDownloadProgressEventArgs e)
        {
            SetSplashScreenProcess(e.ProgressPercent.ToString() + "%");
        }
        // 下载完成后，开始对文件进行处理。
        void downloader_DownloadCompleted(object sender, FileDownloadCompleteEventArgs e)
        {
            try
            {
                D.Debug("下载完成.开始解析");
                // 根据文件下载方式，创建文件解析器。
                IParser parser = ParseFactory.ParserCreator(Files[0].Mode);
                // 通过解析器，对文件进行解析处理。解析之前需要判断是否存在可用的解析器。
                if (parser != null) parser.Parse(Files[0].File,e.MemoryStream);
                D.Debug("解析完成");
            }
            finally
            {
                this.ToDoNext();
            }
        }
        // 触发下载完成事件
        private void OnDownloadComplated()
        {
            this.Hide();
            if (DownloadComplated != null)
            {
                DownloadComplated(this, null);
            }
        }
        #endregion //#region 3.文件下载 相关

        #region 4.请求用户身份 相关
        /// <summary>请求用户身份信息。</summary>
        private void RequestUserIdentity()
        {
            this.GotoRequestUser(); // 切换状态
            RestartDispatcher(); // 重新启动计时器
            SetSplashScreenUri(string.Empty);
            requestTimer.Stop();

            D.Debug("请求身份.");
            currentUser = new Identity()
            {
                Caption = Q.ConfigManager.GetSet("USER_NAME"),
                TeamCaption = Q.ConfigManager.GetSet("USER_WORKTEAM"),
                Code = Q.ConfigManager.GetSet("USER_CODE"),
                ID = Q.ConfigManager.GetSet("USER_GROUPS"),
            };

            D.Debug("{0}.{1}.{2}.{3}",
                currentUser.Caption,
                currentUser.TeamCaption,
                currentUser.Code,
                currentUser.ID);

            SetSplashScreenText(LanguageText(REQUEST_USER_SUCCESS));
            Q.DataManager.SetUserData(currentUser);

            this.Initialize();
        }

        #endregion //#region 4.请求用户身份 相关
        
        #region 5.请求用户权限 相关
        // 初始化内容
        private void Initialize()
        {
            D.Debug("请求权限.");
            this.GotoRequestConfig();
            RestartDispatcher(); // 重新启动计时器
            Q.RequestConfig(currentUser.ID, (isSuccess, message) =>
            {
                if (isSuccess)
                {
                    D.Debug("权限请求完成.");
                    // 全部加载完成后触发下载完成事件。
                    this.OnDownloadComplated();
                }
                else
                {
                    this.ShowMessage("权限请求失败",message);
                    this.SetSplashScreenText(LanguageText(REQUEST_OPTION_SUCCESS));
                }
            });
        }
        #endregion //#region 5.请求用户权限 相关

        #region 计时器 相关
        DispatcherTimer requestTimer;
        double proc = 0.0;
        // 初始化并启动计时器
        private void RestartDispatcher()
        {
            requestTimer = new DispatcherTimer();
            requestTimer.Interval = TimeSpan.FromMilliseconds(100);
            requestTimer.Tick += new EventHandler(requestTimer_Tick);
            proc = 0.0;
            requestTimer.Start();
        }
        void requestTimer_Tick(object sender, EventArgs e)
        {
            SetSplashScreenProcess((proc += 0.1).ToString("0.0s"));
        }

        #endregion //#region 计时器 相关

        #region 加载过程动画相关
        private void HideLayoutRoot_Completed(object sender, EventArgs e)
        {
            this.HideLayoutRoot.Stop();
            base.Visibility = Visibility.Collapsed;
        }
        // 关闭下载状态
        private void Hide()
        {
            DispatcherTimer dispatcherTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(20.0)
            };
            dispatcherTimer.Tick += delegate(object s, EventArgs a)
            {
                dispatcherTimer.Stop();
                this.HideLayoutRoot.Begin();
            };
            dispatcherTimer.Start();
        }
        #endregion  // #region 加载过程动画相关

        #region 关于闪屏状态文字
        private void SetSplashScreenText(string text)
        {
            this.PercentageCatalog.Text = text;
        }

        private void SetSplashScreenUri(string text)
        {
            this.PercentageName.Text = text;
        }

        private void SetSplashScreenProcess(string text)
        {
            this.PercentageCounter.Text = text;
        }
        // 切换当前工作状态：切换至请求用户
        private void GotoRequestUser()
        {
            SetSplashScreenText(LanguageText(REQUEST_USER));
            VisualStateManager.GoToState(this, "RequestUser", true); // 转换至请求用户信息状态；
        }
        // 切换当前工作状态：切换至请求配置
        private void GotoRequestConfig()
        {
            SetSplashScreenText(LanguageText(REQUEST_OPTION));
            VisualStateManager.GoToState(this, "RequestConfig", true);
        }
        #endregion //#region 关于闪屏状态文字
    }
}